package cn.com.netedge.iot.frontend.comm.nio;

import cn.com.netedge.iot.common.dataobject.ReceiveFrame;
import cn.com.netedge.iot.common.enums.MessageDirectEnum;
import cn.com.netedge.iot.frontend.comm.utils.DecoderUtil;
import cn.com.netedge.iot.frontend.comm.utils.DeviceLogUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MessageDealHandler extends ChannelInboundHandlerAdapter {
    private static final Logger logger = LoggerFactory.getLogger(MessageDealHandler.class);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (!(msg instanceof ReceiveFrame)) {
            logger.error("msg is not data frame.");
            return;
        }

        ReceiveFrame frame = (ReceiveFrame) msg;
        String channelId = ctx.channel().id().asLongText();

        byte[] reply = DecoderUtil.processFrame(frame, channelId);
        if (reply != null && reply.length > 0) {
            Channel channel = ctx.channel();
            if(channel.isWritable()) {
                channel.writeAndFlush(reply);
            } else {
                logger.warn("channelId:{} write data error.", channelId);
            }
            //记录报文日志
            try {
                DeviceLogUtil.deviceLogger.logMessage(frame.getDeviceNumber(), frame.getDeviceType(), MessageDirectEnum.DOWN, reply);
            } catch (Exception e) {
                logger.info("record rtu log error.", e);
            }
        }
    }
}
